import "package:ct_pa_majordomo/config/theme_vars.dart";
import "package:ct_pa_majordomo/pages/apartment/api.dart";
import "package:ct_pa_majordomo/pages/device/lock/api.dart";
import "package:ct_pa_majordomo/pages/device/widgets/device_header.dart";
import "package:ct_pa_majordomo/utils/stacker.dart";
import "package:ct_pa_majordomo/widgets/button/index.dart";
import "package:ct_pa_majordomo/widgets/divider/solid_divider.dart";
import "package:ct_pa_majordomo/widgets/normal_scaffold/index.dart";
import "package:flutter/cupertino.dart";
import "package:flutter/material.dart";
import "package:flutter_easyloading/flutter_easyloading.dart";

class AssociatedRoom extends StatefulWidget {
  final int lockId;
  final int roomId;
  const AssociatedRoom({super.key, required this.lockId, required this.roomId});

  @override
  State<StatefulWidget> createState() => _AssociatedRoomState();

}

class _AssociatedRoomState extends State<AssociatedRoom> {

  List _list = [];
  Map _filter = {"pageNum": 1, "pageSize": 10, "name": ""};

  bool _associated() {
    return widget.roomId != -1;
  }

  // 获取未关联锁的房间列表
  void _getRooms() async {
    try {
      Map<String, dynamic> params = {..._filter};
      Map resData = await apartmentApi.getRoomList(params);
      setState(() {
        _list = resData["data"] ?? [];
      });
    } catch (error) {
      print(error);
    }
  }

  void _getRoomInfo() async {
    try {
      Map resData = await apartmentApi.getRoomInfo(widget.roomId);
      setState(() {
        _list.add(resData["data"]);
      });
    } catch (error) {
      print(error);
    }
  }

  void _associatedRooms(Map room) async {
    Map<String, dynamic> params = {
      "lockId": widget.lockId,
      "roomId": room["roomId"],
    };
    print("params:>>> $params");
    await lockApi.bindRoom(params);
    Map<String, dynamic> editNameParams = {
      "lockId": widget.lockId,
      "lockName": "${room["buildingName"] ?? ""}${room["name"]}",
    };
    await lockApi.editLock(editNameParams);
    EasyLoading.showToast("关联成功");
    if (context.mounted) {
      Navigator.pop(context, true);
    }
  }

  void _unbindRoom() async {
    EasyLoading.show();
    await lockApi.unbindRoom(widget.lockId);
    EasyLoading.showToast("解绑成功");
    Stacker.pop(true);
  }

  @override
  void initState() {
    if (!_associated()) {
      _getRooms();
    } else {
      _getRoomInfo();
    }
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    return DeviceHeader(
      title: "关联的房间",
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new),
        onPressed: () {
          Navigator.pop(context);
        },
      ),
      showSearch: false,
      showFloatBtn: false,
      children: [
        Container(
          padding: EdgeInsets.only(top: !_associated() ? 60 : 0, bottom: _associated() ? 78 : 0),
          child: ListView.separated(
            itemBuilder: (context, index) {
              return Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                decoration: const BoxDecoration(
                  color: Colors.white,
                ),
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: !_associated() ? () {
                    _associatedRooms(_list[index]);
                  } : null,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(_list[index]["name"]),
                      if (!_associated()) const Icon(Icons.circle_outlined, color: ThemeVars.colorPrimary,)
                    ],
                  ),
                ),
              );
            },
            separatorBuilder: (context, index) => const SolidDivider(padding: EdgeInsets.only(left: 12)),
            itemCount: _list.length
          ),
        ),
        if (!_associated()) Positioned(
            width: MediaQuery.of(context).size.width,
            top: 0,
            left: 0,
            child: Container(
                width: MediaQuery.of(context).size.width,
                decoration: const BoxDecoration(
                  color: ThemeVars.colorBackground,
                ),
                child: Column(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 6),
                      decoration: const BoxDecoration(
                          color: Colors.white
                      ),
                      child: SizedBox(
                        height: 40,
                        child: TextFormField(
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(
                                borderRadius: BorderRadius.all(Radius.circular(5)),
                                borderSide: BorderSide.none
                            ),
                            hintText: "请输入",
                            isDense: true,
                            filled: true,
                            fillColor: ThemeVars.colorBackground,
                            suffixIcon: SizedBox(
                              child: Icon(Icons.search, size: 20,),
                            ),
                          ),
                          style: TextStyle(fontSize: 14),
                          initialValue: _filter["name"],
                          onChanged: (value) {
                            setState(() {
                              _filter["name"] = value;
                              _filter["pageNum"] = 1;
                              _getRooms();
                            });
                          },
                        ),
                      ),
                    ),
                    const SizedBox(height: 10, child: DecoratedBox(decoration: BoxDecoration(color: ThemeVars.colorBackground)),)
                  ],
                )
            )
        ),
        if (_associated()) Positioned(
            bottom: 0,
            left: 0,
            width: MediaQuery.of(context).size.width,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: ThemeVars.paddingPage, vertical: 16),
              decoration: const BoxDecoration(
                  color: Colors.white,
                  boxShadow: [ThemeVars.boxShadow]
              ),
              child: Button(
                  type: ButtonType.primary,
                  onPressed: () {
                    _unbindRoom();
                  },
                  child: const Text("解除关联")
              ),
            )
        ),
      ],
    );
  }

}